package com.cuoyi.coupon.mall.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuoyi.coupon.mall.common.ApiResult;
import com.cuoyi.coupon.mall.common.BusinessException;
import com.cuoyi.coupon.mall.constant.BusinessConstant;
import com.cuoyi.coupon.mall.constant.ImageConstant;
import com.cuoyi.coupon.mall.enums.ErrorEnum;
import com.cuoyi.coupon.mall.model.req.TransCodeAddReq;
import com.cuoyi.coupon.mall.model.req.TransCodeCouponReq;
import com.cuoyi.coupon.mall.model.req.TransCodePageReq;
import com.cuoyi.coupon.mall.model.res.TransCodeAppResp;
import com.cuoyi.coupon.mall.model.res.TransCodePageResp;
import com.cuoyi.coupon.mall.model.res.TransCodeResp;
import com.cuoyi.coupon.mall.mybatis.entity.TransCode;
import com.cuoyi.coupon.mall.mybatis.mapper.TransCodeMapper;
import com.cuoyi.coupon.mall.service.TransCodeService;
import com.cuoyi.coupon.mall.utils.PageUtil;
import com.cuoyi.coupon.mall.utils.QrCodeUtil;
import com.cuoyi.coupon.mall.utils.TransCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.net.BindException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 转码数据（含二维码转码和券码转码） 服务实现类
 * </p>
 *
 * @author Mybatis Plus Generator
 * @since 2022-03-04 11:15:48
 */
@Service
@Slf4j
public class TransCodeServiceImpl extends ServiceImpl<TransCodeMapper, TransCode> implements TransCodeService {

    @Resource
    private TransCodeMapper transCodeMapper;

    @Override
    public void save(TransCodeAddReq transCodeAddReq) {
        //新增
        if (ObjectUtils.isEmpty(transCodeAddReq.getId())) {
            addTransCode(transCodeAddReq);
            return;
        }

        updateTransCode(transCodeAddReq);
    }

    private void updateTransCode(TransCodeAddReq transCodeAddReq) {
        TransCode transCode = new TransCode();
        transCode.setId(transCodeAddReq.getId());
        transCode.setRemark(transCodeAddReq.getRemark());
        transCode.setUpdateTime(LocalDateTime.now());
        transCode.setUpdateUser(transCodeAddReq.getUpdateUser());
        transCode.setStatus(transCodeAddReq.getStatus());
        transCode.setSalesPlatform(transCodeAddReq.getSalesPlatform());
        transCode.setRelationOrder(transCodeAddReq.getRelationOrder());
        transCodeMapper.updateById(transCode);
    }

    private void addTransCode(TransCodeAddReq transCodeAddReq) {
        //按二维码 1
        Integer type = transCodeAddReq.getType();
        if (BusinessConstant.IMAGE_CODE.equals(type)) {
            //图片列表不能为空
            if (CollectionUtils.isEmpty(transCodeAddReq.getImageUrls())) {
                throw new BusinessException(ErrorEnum.PARAMS_ERROR.code(), "二维码数据不能为空！");
            }

            saveTransCodeByImageCode(transCodeAddReq);
        }

        //按券码 2
        saveTransCodeByCouponNo(transCodeAddReq);
    }

    private void saveTransCodeByCouponNo(TransCodeAddReq transCodeAddReq) {
        for (TransCodeCouponReq transCodeCouponReq : transCodeAddReq.getTransCodeCouponReqs()) {
            TransCode transCode = new TransCode();
            transCode.setCouponNo(transCodeCouponReq.getCouponNo());
            transCode.setCouponPassword(transCodeCouponReq.getCouponPassword());
            commonInsert(transCodeAddReq, transCode);
        }
    }

    private void commonInsert(TransCodeAddReq transCodeAddReq, TransCode transCode) {
        transCode.setTransCodeNo(acquireTransCodeNo());
        transCode.setBrandId(transCodeAddReq.getBrandId());
        transCode.setBrandName(transCodeAddReq.getBrandName());
        transCode.setRealValid(transCodeAddReq.getRealValid());
        transCode.setPromptValid(transCodeAddReq.getPromptValid());
        transCode.setCreateUser(transCodeAddReq.getCreateUser());
        transCode.setCreateTime(LocalDateTime.now());
        transCode.setType(transCodeAddReq.getType());
        transCode.setStatus(0);
        transCode.setMark(0);
        transCodeMapper.insert(transCode);
    }

    private String acquireTransCodeNo() {
        Integer count = transCodeMapper.selectLastOne();
        return TransCodeUtils.transCodeNoGenerator(count);
    }

    private void saveTransCodeByImageCode(TransCodeAddReq transCodeAddReq) {
        for (String imageUrl : transCodeAddReq.getImageUrls()) {
            TransCode transCode = new TransCode();
            transCode.setImageUrl(imageUrl);
            transCode.setCouponNo(acquireCouponNo(imageUrl));
            commonInsert(transCodeAddReq, transCode);
        }
    }

    private String acquireCouponNo(String url) {
        try {
            String filename = url.split("=")[1];
            return QrCodeUtil.decodeQrCode(new FileInputStream(ImageConstant.DIR_DEV + filename));
        } catch (Exception e) {
            log.error("acquireCouponNo error......", e);
        }
        return "";
    }

    @Override
    public TransCodePageResp getPageTransCode(TransCodePageReq transCodeAddReq) {
        log.info("getPageTransCode......page:" + transCodeAddReq.getPage());

        String brandName = transCodeAddReq.getBrandName();
        Integer status = transCodeAddReq.getStatus();
        String couponNo = transCodeAddReq.getCouponNo();
        String startTime = transCodeAddReq.getStartTime();
        String endTime = transCodeAddReq.getEndTime();

        Map<String, Object> params = new HashMap<>(2 << 3);
        //商品货号
        params.put("brandName", brandName);
        //店铺id
        params.put("status", status);
        //商品名称
        params.put("couponNo", couponNo);
        //店铺自定义分类
        params.put("startTime", startTime);
        //品牌id
        params.put("endTime", endTime);

        List<TransCodeResp> transCodeRespList = transCodeMapper.getPageTransCode(params);
        TransCodePageResp transCodePageResp = new TransCodePageResp();
        transCodePageResp.setCount(transCodeRespList.size());
        transCodePageResp.setTransCodeRespList(PageUtil.getPageList(transCodeAddReq.getPage(), transCodeAddReq.getRows(), transCodeRespList));
        return transCodePageResp;
    }

    @Override
    public TransCodeAppResp getAppData(String transCode) {
        if (Objects.isNull(transCode)) {
            throw new BusinessException(ErrorEnum.PARAMS_ERROR.code(), ErrorEnum.PARAMS_ERROR.message());
        }

        LambdaQueryWrapper<TransCode> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(TransCode::getTransCodeNo, transCode);
        queryWrapper.eq(TransCode::getStatus, 0);
        return Convert.convert(TransCodeAppResp.class, transCodeMapper.selectOne(queryWrapper));
    }

}
